package com.linchaoen.elema.controller;

import com.linchaoen.elema.model.entity.Order;
import com.linchaoen.elema.model.request.OrderRequest;
import com.linchaoen.elema.service.OrderService;
import com.linchaoen.elema.utils.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/api/v1/pri/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @GetMapping("buy")
    public JsonData buy(HttpServletRequest request, @RequestBody OrderRequest orderRequest) {
        Integer uid = (Integer) request.getAttribute("uid");
        Integer fid = orderRequest.getFoodId();
        Integer num = orderRequest.getNum();

        System.out.println(uid + " " + fid);

        int rows = orderService.saveOrder(uid, fid, num);
        return rows == 1 ? JsonData.buildSuccess("购买成功") : JsonData.buildError("购买失败");
    }

    @GetMapping("get_order_by_id")
    public JsonData getOrderByUserId(HttpServletRequest request) {

        int uid = (Integer) request.getAttribute("uid");

        List<Order> orderList = orderService.findOrderByUid(uid);

        return JsonData.buildSuccess(orderList);

    }

    @GetMapping("save_order")
    public JsonData saveOrder(HttpServletRequest request,
                              @RequestParam(value = "food_id")Integer foodId,
                              @RequestParam(value = "num") Integer num) {
        Integer uid = (Integer) request.getAttribute("uid");

        System.out.println(uid + " " + foodId);

        int rows = orderService.saveOrder(uid, foodId, num);
        return rows == 1 ? JsonData.buildSuccess("购买成功") : JsonData.buildError("购买失败");
    }

}
